<?php

class SelfFoodController extends SelfController {

    static $model_name = 'food';
    static $display_name = '餐品';

    private $orderService = null;
	/*
	|--------------------------------------------------------------------------
	| Default Home Controller
	|--------------------------------------------------------------------------
	|
	| You may wish to use controllers instead of, or in addition to, Closure
	| based routes. That's great! Here is an example controller method to
	| get you started. To route to this controller, just add the route:
	|
	|	Route::get('/', 'HomeController@showWelcome');
	|
	*/

	public function getIndex()
	{

        $result =  $this->getService()->getList(array(), 8);
        $entries = $result['entries'];
        $links = $result['links'];

        $menu_id = Input::get( 'menu_id', null );
        $title = '全部餐品';
        if(!empty($menu_id)){
            $title = Menu::where('id', $menu_id)->select('name')->get()->first()->name;
        }
        $menus = Menu::select('id','name')->get();

        return View::make(self::$view_path.'.'.self::$model_name.'.list', compact('entries','menus', 'title', 'links'));
	}

    public function getDetail($entry){
        $thumbPaths = [];
        foreach($entry->thumbs as $thumb){
            array_push($thumbPaths, $thumb->path);
        }

        return json_encode(array('result'=>true, 'entry'=>$entry, 'thumbs'=>$thumbPaths));
    }

    public function doOrder(){
        $params = Input::get('datas');
        $arrParam = json_decode(str_replace('\\','',$params));

        if(empty($arrParam)){
            return json_encode(array('result'=>false, 'msg'=>'不允许传空参数！'));
        }

        if(!isset($arrParam->food_ids) || !isset($arrParam->counts) || !isset($arrParam->total_price)){
            return json_encode(array('result'=>false, 'msg'=>'没有food_ids或者counts或者total_price 参数'));
        }

        $foodIds = $arrParam->food_ids;
        $counts = $arrParam->counts;
        $totalPrice = $arrParam->total_price;

        if(!is_array($foodIds)){
            return json_encode(array('result'=>false, 'msg'=>'不允许生成空订单！'));
        }

        $order = $this->getOrderService()->createOrder($this->member, $foodIds, $counts, $totalPrice);
        if(!$order){
            return json_encode(array('result'=>false, 'msg'=>$this->getOrderService()->errors()->getMessages()));
        }
        return json_encode(array('result'=>true, 'msg'=>'下单成功！', 'order_id'=>$order->id));
    }

    public function getService() {
        if(is_null($this->service)){
            $this->service = new SelfFoodService();
        }
        return $this->service;
    }

    public function getOrderService() {
        if(is_null($this->orderService)){
            $this->orderService = new SelfOrderService();
        }
        return $this->orderService;
    }

}
